package cn.felord.oss;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.ObjectMetadata;
import org.springframework.util.Assert;

import java.io.InputStream;
import java.util.Map;

/**
 *
 * @author Administrator
 * @since 2025/11/3 15:36
 */
public class TencentStorage implements Storage {

    private final Map<String, COSClient> cosClientMap;

    public TencentStorage(Map<String, COSClient> cosClientMap) {
        this.cosClientMap = cosClientMap;
    }

    @Override
    public void putObject(String bucketName, String objectName, InputStream inputStream, String contentType) throws Exception {
        COSClient cosClient = cosClientMap.get(bucketName);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(contentType);
        Assert.notNull(cosClient, "cos bucket " + bucketName + " not found");
        cosClient.putObject(bucketName, objectName, inputStream, metadata);
    }

    @Override
    public InputStream getObject(String bucketName, String objectName) throws Exception {
        COSClient cosClient = cosClientMap.get(bucketName);
        Assert.notNull(cosClient, "cos bucket " + bucketName + " not found");
        COSObject object = cosClient.getObject(bucketName, objectName);
        if (object != null) {
            return object.getObjectContent();
        }
        return null;
    }

    @Override
    public String getObjectUrl(String bucketName, String objectName) throws Exception {
        COSClient cosClient = cosClientMap.get(bucketName);
        Assert.notNull(cosClient, "cos bucket " + bucketName + " not found");
        return cosClient.getObjectUrl(bucketName,objectName).toString();
    }

    @Override
    public void removeObject(String bucketName, String objectName) throws Exception {
        COSClient cosClient = cosClientMap.get(bucketName);
        Assert.notNull(cosClient, "cos bucket " + bucketName + " not found");
        cosClient.deleteObject(bucketName, objectName);
    }
}
